package com.lzs.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzs.entity.Dept;
import com.lzs.entity.User;
import com.lzs.system.mapper.DeptMapper;
import com.lzs.system.mapper.MenuMapper;
import com.lzs.system.mapper.RoleMapper;
import com.lzs.system.mapper.UserMapper;
import com.lzs.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzs.util.ActivierUser;
import com.lzs.system.vo.LoginVO;
import com.lzs.util.MD5Util;
import com.lzs.util.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author 刘中帅
 * @since 2020-11-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private  UserMapper userMapper;
    @Autowired
    private DeptServiceImpl deptService;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public Page<User> selectAllUserPage(Integer page, Integer limit, User user) {
        // 分页类
        Page<User> userPage=new Page<>(page,limit);
        String info = user.getInfo();

        // 查询条件类
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        if(StringUtils.isNotEmpty(info)){
             queryWrapper.like("name", info).or();
        }
        if(StringUtils.isNotEmpty(info)){
            queryWrapper.like("phone", info).or();
        }
        if(StringUtils.isNotEmpty(info)){
             queryWrapper.like("account", info).or();
        }
        if (user.getDeptId()!=null){
            // 前台点击部门树时触发查询
            List<Dept> depts = deptMapper.selectList(null);
            List<Dept> child = deptService.selectChild(user.getDeptId(), depts);
            List<Long> list = child.stream().map(item -> item.getDeptId()).collect(Collectors.toList());
            list.add(user.getDeptId());
            System.out.println(list);
            queryWrapper.in("dept_id",list);
        }
        userMapper.selectPage(userPage,queryWrapper);
        System.out.println(userPage.toString());
        return userPage;
    }

    /**
     * 用户新增修改
     * @param user
     * @return
     */
    @Override
    public R insertOrUpdateUser(User user) {
        if (user.getUserId()!=null){
            UpdateWrapper<User> updateWrapper=new UpdateWrapper<>();
            user.setUpdateTime(new Date());
            int i = userMapper.updateById(user);
            if (i>0){
                return R.ok().message("修改成功");
            }
            return R.ok().message("修改失败");
        }else{
            String status = user.getStatus();
            if(!StringUtils.isNotEmpty(status)){
                user.setStatus("DISABLE");
            }
            user.setCreateTime(new Date());
            // 密码加密
            String password = user.getPassword();
            String account = user.getAccount();
            String saltMD5 = MD5Util.getSaltMD5(password, account);
            user.setPassword(saltMD5);
            user.setSalt(account);
            int i = userMapper.insert(user);
            if (i>0){
                return R.ok().message("新增成功");
            }
            return R.ok().message("新增失败");
        }
    }

    /**
     * 改变用户状态
     * @param status
     * @param userId
     * @return
     */
    @Override
    public R updateStatus(Long userId,String status) {
        int i = userMapper.updateStatus(userId, status);
        if (i>0){
            return R.ok();
        }else {
            return R.error();
        }
    }

    /**
     * 查询当前用户拥有的角色
     * @param userId
     * @return
     */
    @Override
    public List<Long> selectRoleByUserId(Long userId) {
        return userMapper.selectRoleByUserId(userId);
    }

    /**
     * 更改当前用户角色
     * @param roles
     * @param userId
     * @return
     */
    @Override
    public R updateRoleByUserId(Long userId,List<Long> roles) {
        if (roles.size() > 0) {
            userMapper.deleteRoleByUserId(userId);
            int i = userMapper.insertRoleByUserId(roles, userId);
            if (i > 0) {
                return R.ok().message("配置成功");
            }
            return R.error().message("配置失败");
        }
        userMapper.deleteRoleByUserId(userId);
        return R.ok().message("配置成功，当前用户无角色");
    }


    //判断账号或密码是否正确以及该用户具有的权限和角色
    @Override
    public ActivierUser selectUserByUserName(LoginVO loginVO) {
        // 判断账号是否正确
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("account",loginVO.getUsername());
        User user = userMapper.selectOne(queryWrapper);
        System.out.println(user.toString());
        // 判断当前账户是否存在
        if (user==null){
            return  null;
        }
        // 判断密码是否正确
        String saltMD5 = MD5Util.getSaltMD5(loginVO.getPassword(), user.getSalt());// 输入密码加盐
        if (!StringUtils.equals(saltMD5,user.getPassword())){
            return null;
        }
        // 根据用户id查询该用户具有的角色，权限；
        List<String> roles = roleMapper.selectRoleByUserId(user.getUserId());
        List<String> permission = menuMapper.queryPermissionByUserId(user.getUserId());
        // 根据用户ID查询所在部门仓库
        List<Long> warehouseId = userMapper.selectWarehouseByUserId(user.getUserId());
        ActivierUser activierUser=new ActivierUser(user,roles,permission,warehouseId);
        return activierUser;
    }

    /**
     * 获取登录用户IP地址
     *
     * @param request
     * @return
     */
    public  String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
//        if (ip.equals("0:0:0:0:0:0:0:1")) {
//            ip = "localhost";
//        }
        return ip;
    }

    /**
     * 修改回显方法
     * @param userId
     * @return
     */
    @Override
    public R findByUserId(Long userId) {
        User user = userMapper.findByUserId(userId);
        return R.ok().data("user",user);
    }

    /**
     * 用户重置密码
     * @param user
     * @return
     */
    @Override
    public R resetPwd(User user) {
        String password = "123456";
        String account = user.getAccount();
        String saltMD5 = MD5Util.getSaltMD5(password, account);
        user.setPassword(saltMD5);
        int i = userMapper.updateById(user);
        if (i>0){
            return R.ok().message("重置成功");
        }
        return R.ok().message("重置失败");
    }
}
